package com.zho.util.rctrl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

import com.zho.util.Logit;

public class RemoteControl implements Runnable {

	private static Logit log = Logit.getInstance(RemoteControl.class);
	private Vector services;

	private ServerSocket listener;

	private boolean stop;

	private ServiceManager serviceManager;

	public RemoteControl(int port, String strPropFileName) throws IOException {
		stop = false;
		Service.prepareMethods(strPropFileName);
		services = new Vector();
		listener = new ServerSocket(port);
		serviceManager = new ServiceManager(services);
		serviceManager.start();
		log.info("RemoteControl started     port:[" + port + "]");
	}

	public void stop() {
		stop = true;
	}

	public void run() {

		while (!stop) {
			Socket socket;

			try {
				socket = listener.accept();
			} catch (IOException e) {
				log.info("IOException when listening: " + e.toString());
				stop();
				break;
			}

			try {
				Service service = new Service(socket);
				services.add(service);
				service.start();
			} catch (IOException e) {
				log.info("IOException when creating service: " + e.toString());
			}
		}

		log.info("Remote Control stopping...");

		// stop services
		try {
			Iterator iter = services.iterator();
			while (iter.hasNext()) {
				Service service = (Service) iter.next();
				service.stopService();
			}
			while (services.size() > 0) {
				rest(1000);
			}
			serviceManager.stopServiceManager();
			while (serviceManager.isAlive()) {
				rest(1000);
			}
		} catch (InterruptedException e) {
			log.error(e.getMessage(), e);
		}

		// close listener
		try {
			listener.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}

		log.info("Remote Control stopped...");

	}

	synchronized void rest(int miliSeconds) throws InterruptedException {
		wait(miliSeconds);
	}
}
